/**
 * Copyright (C) 2013 DaiKit.com - daikit4gxt module (admin@daikit.com)
 *
 *         Project home : http://code.daikit.com/daikit4gxt
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.daikit.daikit4gxt.server.rpc;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.daikit.commons.shared.exception.DkException;
import com.daikit.commons.shared.exception.context.DkExceptionContext;
import com.daikit.daikit4gxt.server.gwtspring.GwtRpcRemoteServletWrapper;
import com.sencha.gxt.data.shared.SortDir;


/**
 * Abstract RPC class that all application RPCs should extend.
 * 
 * @author tcaselli
 * @version $Revision$ Last modifier: $Author$ Last commit: $Date$
 */
public abstract class AbstractBaseRpcImpl
{

	private static Log log = LogFactory.getLog(AbstractBaseRpcImpl.class);

	@Autowired
	private GwtRpcRemoteServletWrapper gwtRpcRemoteServletWrapper;

	/**
	 * Handle request and forward it to GwtRpcAdapter
	 * 
	 * @param request
	 *           the {@link HttpServletRequest}
	 * @param response
	 *           the {@link HttpServletResponse}
	 * @return null
	 * @throws Exception
	 */
	@RequestMapping(value = "")
	public ModelAndView handleRequest(final HttpServletRequest request, final HttpServletResponse response) throws Exception
	{
		onBeforeHandleRequest();
		gwtRpcRemoteServletWrapper.handleRequest(request, response, this);
		return null;
	}

	protected void onBeforeHandleRequest() throws DkException
	{
		// Nothing done by default
	}

	// METHODS

	/**
	 * Encapsulate all not {@link GwtLibRpcException} in a {@link GwtLibRpcException} with code
	 * {@link StandardErrorCodes.UNKNWOWN_ERROR} for not {@link SecurityException}
	 * 
	 * @param e
	 *           the exception to encapsulate (if not null)
	 * @throws GwtLibRpcException
	 *            if give, exception is not null.
	 */
	private final void processNotApplicationSpecificError(final Exception e) throws DkException
	{
		if (e == null)
		{
			return;
		}
		//		if (GwtLibException.class.equals(e.getClass()))
		if (e instanceof DkException)
		{
			log.error(e.getMessage(), e);
			throw (DkException) e;
		}
		// Create GwtLibRpcException from other Exceptions part of the normal process (not unexpected exceptions)
		if (SecurityException.class.equals(e.getClass()))
		{
			log.error(e.getMessage(), e);
			throw new DkException(new DkExceptionContext(e.getMessage()), e);
		}
		// if we are here that's because handleApplicationSpecificException(e) didn't handle
		// the given exception e. So a unknown exception is thrown.
		log.error(DkException.UNKNWOWN_ERROR_MESSAGE, e);
		throw new DkException(new DkExceptionContext(DkException.UNKNWOWN_ERROR_MESSAGE), e);
	}

	protected void populateException(final DkException exception)
	{
		final DkExceptionContext context = exception.getContext();
		if (context.getCreationDate() == null)
		{
			context.setCreationDate(new Date().toString());
		}
		if (context.getRequest() == null)
		{
			final StringBuffer requestURL = getRequest().getRequestURL();
			if (getRequest().getQueryString() != null)
			{
				requestURL.append("?").append(getRequest().getQueryString());
			}
			final String completeURL = requestURL.toString();
			context.setRequest(completeURL);
		}
		if (context.getLanguageIsoCode() == null)
		{
			context.setLanguageIsoCode(getLanguageIsoCode());
		}
		if (context.getUserLogged() == null)
		{
			context.setUserLogged(getUserLogged());
		}
		context.buildStackTrace(exception);
	}

	/**
	 * Method to be overridden (and called at the end of the overriding method) to provide custom error handling.
	 * 
	 * @param e
	 *           the exception risen in the RPC.
	 * @throws GwtLibRpcException
	 *            the created throw-able {@link GwtLibRpcException} exception for the risen exception.
	 */
	protected final void processError(final Exception e) throws DkException
	{
		try
		{
			processApplicationSpecificException(e);
			processNotApplicationSpecificError(e);
		}
		catch (final DkException exception)
		{
			populateException(exception);
			throw exception;
		}
	}

	/**
	 * Retrieve current HTTP request.
	 * 
	 * @return the current HTTP request.
	 */
	protected final HttpServletRequest getRequest()
	{
		return gwtRpcRemoteServletWrapper.getRequest();
	}

	/**
	 * Retrieve current HTTP response.
	 * 
	 * @return the current HTTP response.
	 */
	protected final HttpServletResponse getResponse()
	{
		return gwtRpcRemoteServletWrapper.getResponse();
	}

	/**
	 * Utility method for paging.
	 * 
	 * @param sortDir
	 *           the GXT sort direction.
	 * @return {@link Boolean.TRUE} if sort is ascending , {@link Boolean.FALSE} if sort is descending, null otherwise.
	 */
	protected final Boolean isSortAsc(final SortDir sortDir)
	{
		return sortDir == null ? null : sortDir.equals(SortDir.ASC) ? Boolean.TRUE : Boolean.FALSE;
	}

	protected abstract String getLanguageIsoCode();

	protected abstract String getUserLogged();

	protected abstract void processApplicationSpecificException(final Exception e) throws DkException;

}
